package main.Parallel;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class OperationQueueManager {
    private List<OperationQueue> jobQueues;
    private Iterator<OperationQueue> iterator;
    
    public OperationQueueManager(int cores) {
        this.jobQueues = new ArrayList<OperationQueue>(cores);
        for(int i = 0; i < cores; i++) {
            OperationQueue q = new OperationQueue();
            q.start();
            this.jobQueues.add(q);
            this.iterator = jobQueues.iterator();
        }
    }
    
    private synchronized OperationQueue next() {
        if(iterator.hasNext()) {
            return iterator.next();
        }
        else {
            iterator = jobQueues.iterator();
            if(iterator.hasNext()) {
                return iterator.next();
            }
            else {
                throw new RuntimeException("No queues, what happened??");
            }
        }
    }
    
    public synchronized void addJob(OperationQueueJob job) {
        this.next().addJob(job);
    }
}
